package com.sdk.bigdata.utils;


import com.sdk.bigdata.constant.Constants;
import org.slf4j.Logger;

public class LoggerUtil {
    private static volatile int LOG_LEVEL = 4;

    static void setLogLevel(String logLevel) {
        if (null == logLevel || logLevel.equals("")) {
            // 则不进行日志打印
            LOG_LEVEL = 99;
        } else {
            LOG_LEVEL = getLogLevel(logLevel);
        }
    }

    private static int getLogLevel(String logLevel) {
        switch (logLevel.toUpperCase()) {
            case Constants.INFO:
                return Constants.INFO_LEVEL;
            case Constants.WARN:
                return Constants.WARN_LEVEL;
            case Constants.DEBUG:
                return Constants.DEBUG_LEVEL;
            default:
                return Constants.ERROR_LEVEL;
        }
    }

    public static void log(Logger logger, String logLevel, String msg) {
        if (logger != null && logLevel != null) {
            try {
                if (getLogLevel(logLevel) >= LOG_LEVEL) {
                    switch (logLevel.toUpperCase()) {
                        case Constants.INFO:
                            logger.info(printStackTrace() + msg);
                            break;
                        case Constants.WARN:
                            logger.warn(printStackTrace() + msg);
                            break;
                        case Constants.DEBUG:
                            logger.debug(printStackTrace() + msg);
                            break;
                        case Constants.ERROR:
                            logger.error(printStackTrace() + msg);
                            break;
                        default:
                            break;
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    private static String printStackTrace(){
        StackTraceElement[] stackTraceElements = Thread.currentThread().getStackTrace();
        if (stackTraceElements.length >= 4) {
            return stackTraceElements[3].getMethodName()  +" - "+ stackTraceElements[3].getLineNumber() + " - ";
        }
        return "";
    }
}

